<template>
  <div class="p-6px">
    <el-card class="rounded-md" shadow="never">
      <el-form ref="formRef" :rules="rules" :model="form" label-width="80px" status-icon>
        <el-tabs v-model="activeName" class="demo-tabs">
          <el-tab-pane label="基础配置" name="1">
            <el-row>
              <el-col :xs="{ span: 12 }" :sm="{ span: 12 }">
                <el-form-item label="商品名称" prop="name">
                  <el-input v-model="form.name" placeholder="请输入商品名称" clearable />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :xs="{ span: 12 }" :sm="{ span: 12 }">
                <el-form-item label="商品分类" prop="category_id">
                  <el-cascader
                    placeholder="请选择商品分类"
                    v-model="form.category_id"
                    :options="selectOptions.category"
                    style="width: 540px"
                  >
                  </el-cascader>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :xs="{ span: 24 }" :sm="{ span: 24 }">
                <el-form-item label="商品品牌" prop="brand_id">
                  <el-select v-model="form.brand_id" placeholder="请选择商品品牌" style="width: 500px">
                    <el-option v-for="(item, index) in selectOptions.brands" :key="index" :label="item.name" :value="item.id" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :xs="{ span: 24 }" :sm="{ span: 24 }">
                <el-form-item label="商品标签" prop="tag_ids">
                  <el-select v-model="form.tag_ids" placeholder="请选择商品标签" style="width: 500px" multiple>
                    <el-option v-for="(item, index) in selectOptions.tags" :key="index" :label="item.name" :value="item.id" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :xs="{ span: 12 }" :sm="{ span: 12 }">
                <el-form-item label="副标题" prop="sub_name">
                  <el-input v-model="form.sub_name" type="textarea" :rows="3" placeholder="请输入副标题" clearable />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :xs="{ span: 12 }" :sm="{ span: 12 }">
                <el-form-item label="单位" prop="unit">
                  <el-input v-model="form.unit" placeholder="请输入单位 如:个" clearable />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :xs="{ span: 24 }" :sm="{ span: 24 }">
                <el-form-item label="商品图" prop="slider_image">
                  <ColeAttachmentList v-model:file-list="form.slider_image" :limit="99" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :xs="{ span: 24 }" :sm="{ span: 24 }">
                <el-form-item label="商品视频" prop="video_src">
                  <ColeAttachmentList v-model:file-list="form.video_src" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :xs="{ span: 24 }" :sm="{ span: 24 }">
                <el-form-item label="是否上架" prop="is_show">
                  <el-radio-group v-model="form.is_show">
                    <el-radio :label="1">上架</el-radio>
                    <el-radio :label="0">下架</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :xs="{ span: 24 }" :sm="{ span: 24 }">
                <el-form-item label="运费设置" prop="freight_type">
                  <el-radio-group v-model="form.freight_type">
                    <el-radio :label="1">包邮</el-radio>
                    <el-radio :label="2">运费模板</el-radio>
                    <el-radio :label="3">固定运费</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row v-if="form.freight_type == 2">
              <el-col :xs="{ span: 12 }" :sm="{ span: 12 }">
                <el-form-item label="运费模板" prop="shipping_tpl_id">
                  <el-select v-model="form.shipping_tpl_id" placeholder="请选择运费模板" style="width: 500px">
                    <el-option
                      v-for="(item, index) in selectOptions.freightTpl"
                      :key="index"
                      :label="item.name"
                      :value="item.id"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row v-if="form.freight_type == 3">
              <el-col :xs="{ span: 12 }" :sm="{ span: 12 }">
                <el-form-item label="固定运费" prop="freight">
                  <el-input type="number" v-model="form.freight" placeholder="请输入运费" />
                </el-form-item>
              </el-col>
            </el-row>
          </el-tab-pane>
          <el-tab-pane label="规格库存" name="2">
            <el-row>
              <el-col :xs="{ span: 24 }" :sm="{ span: 24 }">
                <el-form-item label="商品规格" prop="spec">
                  <el-radio-group v-model="form.spec" :disabled="isEdit">
                    <el-radio :label="1">单规格</el-radio>
                    <el-radio :label="2">多规格</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
            </el-row>
            <div v-if="form.spec == 1">
              <el-row>
                <el-col :xs="{ span: 12 }" :sm="{ span: 12 }">
                  <el-form-item label="售价" prop="price">
                    <el-input v-model="form.price" placeholder="请输入售价" clearable />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :xs="{ span: 12 }" :sm="{ span: 12 }">
                  <el-form-item label="划线价" prop="name">
                    <el-input v-model="form.original_price" placeholder="请输入划线价" clearable />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :xs="{ span: 12 }" :sm="{ span: 12 }">
                  <el-form-item label="成本价" prop="cost_price">
                    <el-input v-model="form.cost_price" placeholder="请输入成本价" clearable />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :xs="{ span: 12 }" :sm="{ span: 12 }">
                  <el-form-item label="库存" prop="stock">
                    <el-input v-model="form.stock" placeholder="请输入库存" clearable />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :xs="{ span: 12 }" :sm="{ span: 12 }">
                  <el-form-item label="商品编号" prop="bar_code">
                    <el-input v-model="form.bar_code" placeholder="请输入商品编号" clearable />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :xs="{ span: 12 }" :sm="{ span: 12 }">
                  <el-form-item label="重量(KG)" prop="weight">
                    <el-input v-model="form.weight" placeholder="请输入重量" clearable />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :xs="{ span: 12 }" :sm="{ span: 12 }">
                  <el-form-item label="体积(M³)" prop="volume">
                    <el-input v-model="form.volume" placeholder="请输入体积" clearable />
                  </el-form-item>
                </el-col>
              </el-row>
            </div>
            <div v-if="form.spec == 2">
              <el-form-item label="规格" prop="user_agreement">
                <ColeSpec :spec="form.specValue" @updateSpec="updateSpec"></ColeSpec>
              </el-form-item>
              <el-form-item label="SKU" prop="user_agreement">
                <ColeSku ref="skuRef" :spec="form.specValue" :sku="form.skuList"></ColeSku>
              </el-form-item>
            </div>
          </el-tab-pane>
          <el-tab-pane label="商品详情" name="3">
            <ColeEditor v-model:content="form.content"></ColeEditor>
          </el-tab-pane>
          <el-tab-pane label="其他配置" name="4">
            <el-form-item label="商品参数" prop="level">
              <div>
                <el-button type="primary" @click="addAttr()" link>新的参数</el-button>
                <el-button type="primary" @click="selectAttrTpl()" link>选择参数模板</el-button>
              </div>
              <el-table :data="form.attr" stripe style="width: 100%" :editable="true" border>
                <el-table-column prop="title" label="参数名称" align="center">
                  <template #default="scope">
                    <el-input type="text" v-model="scope.row.label" clearable style="text-align: center" />
                  </template>
                </el-table-column>
                <el-table-column prop="item" label="参数值" align="center">
                  <template #default="scope">
                    <div style="display: flex; flex-wrap: wrap">
                      <el-input type="text" v-model="scope.row.value" clearable style="text-align: center" />
                    </div>
                  </template>
                </el-table-column>
                <el-table-column prop="item" label="操作" align="center">
                  <template #default="scope">
                    <el-button type="primary" @click="removeAttr(scope.row, scope.$index)" link>删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-form-item>
          </el-tab-pane>
        </el-tabs>
      </el-form>
      <el-button type="danger" @click="prev">上一步</el-button>
      <el-button type="danger" @click="next">下一步</el-button>
      <el-button type="primary" loading-icon="Eleme" :loading="loading" v-throttle="handleConfirm"> 保存 </el-button>
    </el-card>
    <KoiDialog ref="koiDialogRef" title="选择参数模板" :height="60" @koiConfirm="handleSelectAttr" :loading="loading">
      <template #content>
        <el-row>
          <el-select v-model="tplValue" placeholder="请选择参数模板" size="large">
            <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-row>
      </template>
    </KoiDialog>
  </div>
</template>

<script setup lang="ts" name="memberPage">
import { cascaderList } from "@/api/pms/cate/index.ts";
import { add, read, update } from "@/api/pms/goods/index.ts";
import { handleTree } from "@/utils/index.ts";
import { koiMsgBox, koiMsgError, koiNoticeError, koiNoticeSuccess } from "@/utils/koi.ts";
import { onMounted, reactive, ref } from "vue";
import { useRouter } from "vue-router";

import { getAll } from "@/api/freight/freight";
import { getAttrAll } from "@/api/pms/attrtpl";
import { getBrand } from "@/api/pms/brand";
import { getAllTags } from "@/api/pms/tags";

// 数据表格加载页面动画
const loading = ref(false);

const activeName = ref<any>("1");
const skuRef = ref<any>();
const selectOptions = ref<any>({
  category: [],
  brands: [],
  tags: [],
  freightTpl: []
});

const resetSelectOptions = () => {
  selectOptions.value = {
    category: [],
    brands: [],
    tags: [],
    freightTpl: []
  };
};

const next = () => {
  if (activeName.value >= 5) {
    return;
  }
  activeName.value = Number(activeName.value) + 1 + "";
};
const prev = () => {
  if (activeName.value <= 1) {
    return;
  }
  activeName.value = Number(activeName.value) - 1 + "";
};
const isEdit = ref(false);

onMounted(() => {
  resetSelectOptions();
  Promise.all([cascaderList(), getBrand(), getAll(), getAllTags()]).then((res: any) => {
    const category = res[0].data;
    if (category != null && category != undefined && category.length > 0) {
      selectOptions.value.category = handleTree(category, "value", "pid");
    }
    selectOptions.value.brands = res[1].data;
    selectOptions.value.freightTpl = res[2].data;
    selectOptions.value.tags = res[3].data;
  });
  
  const { currentRoute } = useRouter();
  const route = currentRoute.value;
  if (route.query.id) {
    isEdit.value = true;
    handleEcho(route.query.id);
  }
  
});
/** 回显数据 */
const handleEcho = async (id: any) => {
  try {
    const res: any = await read(id);
    form.value = res.data;
  } catch (error) {
    koiNoticeError("数据获取失败，请刷新重试");
    console.log(error);
  }
};

/** 确定  */
const handleConfirm = () => {
  if (!formRef.value) return;
  loading.value = true;
  (formRef.value as any).validate(async (valid: any) => {
    if (valid) {
      try {
        if (form.value.spec == 2) {
          form.value.skuList = skuRef.value.getSkuList();
          //过滤空值
          form.value.specValue = form.value.specValue.filter((r: any) => {
            r.item = r.item.filter((item: any) => item && item !== "");
            return r.item && r.title;
          });
        } else {
          form.value.skuList = [];
          form.value.specValue = [];
        }
        if (form.value.category_id) {
          form.value.cate_id1 = form.value.category_id[0] || 0;
          form.value.cate_id2 = form.value.category_id[1] || 0;
          form.value.cate_id3 = form.value.category_id[2] || 0;
        }

        if (form.value.id != null && form.value.id != "") {
          await update(form.value);
        } else {
          await add(form.value);
        }
        koiNoticeSuccess("操作成功");
        // resetForm();
      } catch (error) {
        console.log(error);
        koiNoticeError("操作失败，请刷新重试");
      } finally {
        loading.value = false;
      }
    } else {
      koiMsgError("验证失败，请检查填写内容");
      loading.value = false;
    }
  });
};
const updateSpec = (specValue: any) => {
  form.value.specValue = specValue;
};

// form表单Ref
const formRef = ref<any>();

// form表单
let form = ref<any>({
  name: "",
  sub_name: "",
  cate_id1: "",
  cate_id2: "",
  cate_id3: "",
  unit: "",
  is_show: 1,
  freight_type: 1,
  slider_image: [] as any,
  video_src: [] as any,
  price: 0,
  content: "",
  cost_price: 0,
  original_price: 0,
  postage: 0,
  stock: 0,
  weight: 0,
  volume: 0,
  spec: 1,
  specValue: [],
  skuList: [],
  attr: []
});

/** 表单规则 */
const rules = reactive({
  name: [{ required: true, message: "请输入商品名称", trigger: "blur" }],
  category_id: [{ required: true, message: "请选择商品分类", trigger: "blur" }],
  brand_id: [{ required: true, message: "请选择商品品牌", trigger: "blur" }],
  unit: [{ required: true, message: "请输入单位", trigger: "blur" }],
  slider_image: [{ required: true, message: "请选择商品图片", trigger: "blur" }],
  spec: [{ required: true, message: "请选择商品规格", trigger: "blur" }],
  is_show: [{ required: true, message: "请选择是否上架", trigger: "blur" }],
  freight_type: [{ required: true, message: "请选择运费设置", trigger: "blur" }],
  shipping_tpl_id: [{ required: true, message: "请选择运费模板", trigger: "blur" }],
  freight: [{ required: true, message: "请输入运费金额", trigger: "blur" }]
});

const removeAttr = (_row: any, valueIndex: any) => {
  form.value.attr.splice(valueIndex, 1);
};
const addAttr = () => {
  form.value.attr.push({
    label: "",
    value: ""
  });
};

const tplValue = ref<any>(null);
const options = ref<any>([]);
const koiDialogRef = ref<any>();

const selectAttrTpl = () => {
  koiDialogRef.value.koiOpen();
  getAttrAll().then((r: any) => {
    options.value = r.data.map((r: any) => {
      return {
        label: r.name,
        value: r.id,
        data: r.value
      };
    });
  });
};

const handleSelectAttr = () => {
  koiMsgBox("您确认选择该参数模板吗?这将会覆盖你现有的商品参数")
    .then(async () => {
      const res = options.value.find((r: any) => r.value === tplValue.value);
      if (res) {
        form.value.attr = res.data;
      }
      koiDialogRef.value.koiClose();
    })
    .catch((_r: any) => {});
};
</script>

<style lang="scss" scoped></style>
